import numpy as np
import matplotlib.pyplot as plt
from keras.models import load_model
from keras.datasets import mnist

# 1. 加载模型
model = load_model('mnist_model.keras')

# 2. 加载 MNIST 测试集
(_, _), (x_test, y_test) = mnist.load_data()

# 3. 随机选择三张图片索引
random_indices = np.random.choice(x_test.shape[0], 3, replace=False)

# 4. 显示和预测
for index in random_indices:
    # 准备图片
    img = x_test[index].astype('float32') / 255.0  # 归一化
    img_reshaped = np.reshape(img, (1, 28, 28))  # 增加批量维度

    # 进行预测
    predictions = model.predict(img_reshaped)
    predicted_class = np.argmax(predictions, axis=1)
    confidence_scores = predictions[0] * 100  # 转换为百分比形式

    # 绘制图片
    plt.imshow(img, cmap='gray')
    plt.title(f'Predicted digit: {predicted_class[0]} with confidence: {confidence_scores[predicted_class[0]]:.2f}%')
    plt.axis('off')  # 不显示坐标轴
    plt.show()

    # 显示每个数字的置信度
    for i in range(10):
        print(f'Confidence for digit {i}: {confidence_scores[i]:.2f}%')